package shop.core.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class WriteToHtmlUtils {
    protected static final Logger logger = LoggerFactory.getLogger(WriteToHtmlUtils.class);

    /**
     * 根据ftl模板文件生成静态化路径
     * @param ftlName flt文件名称
     * @param dataModel 数据键值对
     * @param htmlPath 生成文件夹在webapp下的目录名称
     * @throws Exception
     */
    public static void CreateHtmlFile(HttpServletRequest request, String ftlName, Map dataModel, String htmlPath) throws Exception {
        String rootPath = request.getSession().getServletContext().getRealPath("");
        String ftlPath = rootPath + "/WEB-INF/views/front";
        Configuration configuration = new Configuration();
        configuration.setDirectoryForTemplateLoading(new File(ftlPath));
        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate(ftlName);
        String outFilePath= rootPath+htmlPath+".html";
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFilePath), "UTF-8");
        PrintWriter printWriter = new PrintWriter(writer);
        template.process(dataModel, printWriter);
        printWriter.close();
    }

    /**
     * 根据ftl模板文件生成静态化路径
     * @param ftlName flt文件名称
     * @param dataModel 数据键值对
     * @param htmlPath 生成文件夹在webapp下的目录名称
     * @throws Exception
     */
    public static void CreateHtmlFile(String rootPath, String ftlName, Map dataModel, String htmlPath) throws Exception {
        String ftlPath = rootPath + "/WEB-INF/views/front";
        Configuration configuration = new Configuration();
        configuration.setDirectoryForTemplateLoading(new File(ftlPath));
        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate(ftlName);
        String outFilePath= rootPath+htmlPath+".html";
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFilePath), "UTF-8");
        PrintWriter printWriter = new PrintWriter(writer);
        template.process(dataModel, printWriter);
        printWriter.close();
    }
}
